package com.health.config;


import com.health.entity.Admin;
import com.health.service.IAdminService;
import com.health.service.ITPermisionService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpSession;
import java.util.Set;

public class AdminRealm extends AuthorizingRealm {

    @Autowired
    private IAdminService iAdminService;
    @Autowired
    private ITPermisionService itPermisionService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Set<String> permissions = itPermisionService.findPermissionsByAccount(principalCollection.getPrimaryPrincipal().toString());
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setStringPermissions(permissions);
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        Admin admin = iAdminService.dologin(authenticationToken.getPrincipal().toString());
        if (admin == null){
            return null;
        }
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(admin.getUsername(),
                admin.getPassword(),this.getName());
        return simpleAuthenticationInfo;
    }
}
